<template>
    <div ref="canvas"></div>
</template>

<script setup lang="ts">
import { Chart, View } from '@antv/g2';
import { v4 } from 'uuid';
import { onMounted, onUnmounted, ref, shallowRef, watch } from 'vue';

type IDate = { name: string, count: number, color?: string }
const prop = defineProps<{ data: IDate[], height: number }>()
const tclass = v4()
const canvas = ref<HTMLDivElement>()


function rangedata(data: IDate[]): IDate[] {
    return data
}

function getMax() {
    let max = 0;
    prop.data.forEach(({ count }) => {
        if (count > max) {
            max = count
        }
    })
    return max
}


const _chart = shallowRef<View>()

watch(() => prop.data, () => {
    _chart.value?.changeData(rangedata(prop.data));
    _chart.value?.scale('count', {
        min: 0,
        max: getMax() * 1.25,
        alias: '数量',
    });
    _chart.value?.render();

})

onMounted(() => {
    let all = 0
    prop.data.forEach((a) => all = a.count + all)
    if (canvas.value) {
        const chart = new Chart({
            container: canvas.value,
            autoFit: true,
            height: prop.height,
        })
        chart.data(rangedata(prop.data));

        chart.scale('count', {
            min: 0,
            alias: '数量',
        });
        chart.tooltip({
            showMarkers: false,
        });

        // chart.axis('count', {
        //     verticalLimitLength: 100
        // })

        const color = ['#FFFEF7', '#FFF9E6', '#FFF2CC', '#FFEB99', '#FFE066', '#FFD633', '#FFCC00', '#E6B800', '#CC9900', '#B38600', '#997300']
        chart.theme({ "styleSheet": { "brandColor": "#014c63", "paletteQualitative20": color.reverse() } });
        chart
            .interval()
            .position('name*count')
            .label('count', {
            })
            .color('type', () => {
                return '#FF8461';
            })

        _chart.value = chart.interaction(tclass);
        chart.render();
    }

})

onUnmounted(() => {
    if (_chart.value)
        _chart.value.removeInteraction(tclass)
})

defineExpose({
    data: _chart.value
})

</script>